<?php
class ControllerSaleCustomer extends Controller {
	private $error = array();
	public function index() {
		$this->language->load('sale/customer');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('sale/customer');

		$this->getList();
	}

	public function insert() {
		$this->language->load('sale/customer');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('sale/customer');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			try {
				//UPdate level cho thanh vien
				//$this->db->beginTransaction();
				$customer_id = $this->model_sale_customer->addCustomer($this->request->post);
				//Kiem tra: neu thanh vien dong du tien thi tinh hoa hong va cap nhap lai cay.
				if($this->request->post['price'] ==  $this->config->get('config_price')){
					//function cập nhập hoa hồng trực tiếp và hoa hồng gián tiếp cho customer

					$this->addHoaHongTrucTiep($customer_id,$this->request->post['magioithieu'],$this->config->get('config_hh_tructiep'));

					$this->addHoaHongGianTiep($customer_id,$this->request->post['magioithieu'],$this->config->get('config_level'),$this->config->get('config_hh_gian_tiep'))	;
					// Function cập nhập level cho customer trong nhanh
					if(isset($this->request->post['magioithieu']) && $this->request->post['magioithieu']){
						$this->session->data['first_customer_parent'] = $this->request->post['magioithieu'];
						$this->updateNhanh($this->request->post['magioithieu']);
					}
				}
				//$this->db->commit();	
			} catch (Exception $e) {
				//$this->db->rollBack();
			}
			
			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_email'])) {
				$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}
			//todo trint
			$this->redirect($this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getForm();
	}

	public function update() {
		$this->language->load('sale/customer');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('sale/customer');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_sale_customer->editCustomer($this->request->get['customer_id'], $this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_email'])) {
				$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_customer_group_id'])) {
				$url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['filter_approved'])) {
				$url .= '&filter_approved=' . $this->request->get['filter_approved'];
			}

			if (isset($this->request->get['filter_ip'])) {
				$url .= '&filter_ip=' . $this->request->get['filter_ip'];
			}

			if (isset($this->request->get['filter_date_added'])) {
				$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->redirect($this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getForm();
	}

	public function delete() {
		$this->language->load('sale/customer');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('sale/customer');

		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $customer_id) {
				$this->model_sale_customer->deleteCustomer($customer_id);
			}

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_email'])) {
				$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_customer_group_id'])) {
				$url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['filter_approved'])) {
				$url .= '&filter_approved=' . $this->request->get['filter_approved'];
			}

			if (isset($this->request->get['filter_ip'])) {
				$url .= '&filter_ip=' . $this->request->get['filter_ip'];
			}

			if (isset($this->request->get['filter_date_added'])) {
				$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->redirect($this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getList();
	}

	public function approve() {
		$this->language->load('sale/customer');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('sale/customer');

		if (!$this->user->hasPermission('modify', 'sale/customer')) {
			$this->error['warning'] = $this->language->get('error_permission');
		} elseif (isset($this->request->post['selected'])) {
			$approved = 0;

			foreach ($this->request->post['selected'] as $customer_id) {
				$customer_info = $this->model_sale_customer->getCustomer($customer_id);

				if ($customer_info && !$customer_info['approved']) {
					$this->model_sale_customer->approve($customer_id);

					$approved++;
				}
			}

			$this->session->data['success'] = sprintf($this->language->get('text_approved'), $approved);

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_email'])) {
				$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_customer_group_id'])) {
				$url .= '&filter_customer_group_id=' . $this->request->get['filter_customer_group_id'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['filter_approved'])) {
				$url .= '&filter_approved=' . $this->request->get['filter_approved'];
			}

			if (isset($this->request->get['filter_ip'])) {
				$url .= '&filter_ip=' . $this->request->get['filter_ip'];
			}

			if (isset($this->request->get['filter_date_added'])) {
				$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->redirect($this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getList();
	}

	protected function getList() {
		if (isset($this->request->get['filter_madn'])) {
			$filter_madn = $this->request->get['filter_madn'];
		} else {
			$filter_madn = null;
		}
		if (isset($this->request->get['filter_parent'])) {
			$parent_info = $this->model_sale_customer->getCustomerByMaDN($this->request->get['filter_parent']);
			$filter_parent = $parent_info ? $parent_info['customer_id'] : NULL;
		} else {
			$filter_parent = null;
		}
		if (isset($this->request->get['filter_level'])) {
			$filter_level = $this->request->get['filter_level'];
		} else {
			$filter_level = null;
		}
		if (isset($this->request->get['filter_name'])) {
			$filter_name = $this->request->get['filter_name'];
		} else {
			$filter_name = null;
		}

		if (isset($this->request->get['filter_email'])) {
			$filter_email = $this->request->get['filter_email'];
		} else {
			$filter_email = null;
		}

		if (isset($this->request->get['filter_status'])) {
			$filter_status = $this->request->get['filter_status'];
		} else {
			$filter_status = null;
		}

		if (isset($this->request->get['filter_date_added'])) {
			$filter_date_added = $this->request->get['filter_date_added'];
		} else {
			$filter_date_added = null;
		}

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'name';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$url = '';

		if (isset($this->request->get['filter_madn'])) {
			$url .= '&filter_madn=' . urlencode(html_entity_decode($this->request->get['filter_madn'], ENT_QUOTES, 'UTF-8'));
		}
		if (isset($this->request->get['filter_parent'])) {
			$url .= '&filter_parent=' . urlencode(html_entity_decode($this->request->get['filter_parent'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_level'])) {
			$url .= '&filter_level=' . urlencode(html_entity_decode($this->request->get['filter_level'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_email'])) {
			$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['filter_date_added'])) {
			$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
			'separator' => false
		);

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'),
			'separator' => ' :: '
		);

		$this->data['insert'] = $this->url->link('sale/customer/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
		$this->data['delete'] = $this->url->link('sale/customer/delete', 'token=' . $this->session->data['token'] . $url, 'SSL');

		$this->data['customers'] = array();

		$data = array(
			'filter_madn'              => $filter_madn,
			'filter_parent'            => $filter_parent,
			'filter_level'             => $filter_level,
			'filter_name'              => $filter_name,
			'filter_email'             => $filter_email,
			'filter_status'            => $filter_status,
			'filter_date_added'        => $filter_date_added,
			'sort'                     => $sort,
			'order'                    => $order,
			'start'                    => ($page - 1) * $this->config->get('config_admin_limit'),
			'limit'                    => $this->config->get('config_admin_limit')
		);

		$customer_total = $this->model_sale_customer->getTotalCustomers($data);

		$results = $this->model_sale_customer->getCustomers($data);

		foreach ($results as $result) {
			$action = array();

			$action[] = array(
				'text' => $this->language->get('text_edit'),
				'href' => $this->url->link('sale/customer/update', 'token=' . $this->session->data['token'] . '&customer_id=' . $result['customer_id'] . $url, 'SSL')
			);

			$action[] = array(
				'text' => 'Thống kê',
				'href' => $this->url->link('sale/hoahong', 'token=' . $this->session->data['token'] . '&customer_id=' . $result['customer_id'] . $url, 'SSL')
			);
			$action[] = array(
				'text' => 'Xem cấp',
				'href' => $this->url->link('sale/thongkenhanh', 'token=' . $this->session->data['token'] . '&customer_id=' . $result['customer_id'] . $url, 'SSL')
			);
			$color_level = $this->config->get('config_color_level'.$result['level1']);
			$price2 = $this->model_sale_customer->getHistoriesPrice2($result['customer_id']);
			$customer_parent_info = $this->model_sale_customer->getCustomerForHH($result['customer_parent']);
			if((int)$result['level1'] == 0){
				$level = 'Đại lý';
			}elseif((int)$result['level1'] == 1 || (int)$result['level1'] == 2 || (int)$result['level1'] == 3 || (int)$result['level1'] == 4){
				$level = 'Quản Lý ' . (int)$result['level1'];
			} elseif ((int)$result['level1'] == 5) {
				$level = 'Quản lý Pro';
			} else {
				$level = ' Cổ đông Cty';
			}
			$this->data['customers'][] = array(
				'customer_id'    => $result['customer_id'],
				'madn'           => $result['madn'],
				'price'          => $result['price'],
				'level'          => $level,
				'level_default'  => $result['level1'],
				'color_level'    => $color_level,
				'price2'         =>$price2 ?  $this->currency->format($price2['price']) : 0,
				'parent'         =>$customer_parent_info ? $customer_parent_info['madn'] : '',
				'name'           => $result['name'],
				'email'          => $result['email'],
				'status_id'      => $result['status'],
				'status'         => ($result['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),
				'date_added'     => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
				'selected'       => isset($this->request->post['selected']) && in_array($result['customer_id'], $this->request->post['selected']),
				'action'         => $action
			);
		}

		$this->data['heading_title'] = $this->language->get('heading_title');

		$this->data['text_enabled'] = $this->language->get('text_enabled');
		$this->data['text_disabled'] = $this->language->get('text_disabled');
		$this->data['text_yes'] = $this->language->get('text_yes');
		$this->data['text_no'] = $this->language->get('text_no');
		$this->data['text_select'] = $this->language->get('text_select');
		$this->data['text_default'] = $this->language->get('text_default');
		$this->data['text_no_results'] = $this->language->get('text_no_results');

		$this->data['column_name'] = $this->language->get('column_name');
		$this->data['column_email'] = $this->language->get('column_email');
		$this->data['column_customer_group'] = $this->language->get('column_customer_group');
		$this->data['column_status'] = $this->language->get('column_status');
		$this->data['column_approved'] = $this->language->get('column_approved');
		$this->data['column_ip'] = $this->language->get('column_ip');
		$this->data['column_date_added'] = $this->language->get('column_date_added');
		$this->data['column_login'] = $this->language->get('column_login');
		$this->data['column_action'] = $this->language->get('column_action');

		$this->data['button_approve'] = $this->language->get('button_approve');
		$this->data['button_insert'] = $this->language->get('button_insert');
		$this->data['button_delete'] = $this->language->get('button_delete');
		$this->data['button_filter'] = $this->language->get('button_filter');

		$this->data['token'] = $this->session->data['token'];

		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}

		if (isset($this->session->data['success'])) {
			$this->data['success'] = $this->session->data['success'];

			unset($this->session->data['success']);
		} else {
			$this->data['success'] = '';
		}

		$url = '';

		if (isset($this->request->get['filter_madn'])) {
			$url .= '&filter_madn=' . urlencode(html_entity_decode($this->request->get['filter_madn'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_parent'])) {
			$url .= '&filter_parent=' . urlencode(html_entity_decode($this->request->get['filter_parent'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_level'])) {
			$url .= '&filter_level=' . urlencode(html_entity_decode($this->request->get['filter_level'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_email'])) {
			$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}
		if (isset($this->request->get['filter_date_added'])) {
			$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
		}

		if ($order == 'ASC') {
			$url .= '&order=DESC';
		} else {
			$url .= '&order=ASC';
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$this->data['sort_madn'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.madn' . $url, 'SSL');
		$this->data['sort_name'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=ci.name' . $url, 'SSL');
		$this->data['sort_level'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.level' . $url, 'SSL');
		$this->data['sort_email'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.email' . $url, 'SSL');
		$this->data['sort_status'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.status' . $url, 'SSL');
		$this->data['sort_date_added'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . '&sort=c.date_added' . $url, 'SSL');

		$url = '';

		if (isset($this->request->get['filter_madn'])) {
			$url .= '&filter_madn=' . urlencode(html_entity_decode($this->request->get['filter_madn'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_parent'])) {
			$url .= '&filter_parent=' . urlencode(html_entity_decode($this->request->get['filter_parent'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_level'])) {
			$url .= '&filter_level=' . urlencode(html_entity_decode($this->request->get['filter_level'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_customer'])) {
			$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_email'])) {
			$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['filter_date_added'])) {
			$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		$pagination = new Pagination();
		$pagination->total = $customer_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_admin_limit');
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

		$this->data['pagination'] = $pagination->render();

		$this->data['filter_madn'] = $filter_madn;
		$this->data['filter_parent'] = isset($this->request->get['filter_parent']) ? $this->request->get['filter_parent'] : NULL;
		$this->data['filter_level'] = $filter_level;
		$this->data['filter_name'] = $filter_name;
		$this->data['filter_email'] = $filter_email;
		$this->data['filter_status'] = $filter_status;
		$this->data['filter_date_added'] = $filter_date_added;

		$this->load->model('setting/store');

		$this->data['stores'] = $this->model_setting_store->getStores();

		$this->data['sort'] = $sort;
		$this->data['order'] = $order;

		$this->template = 'sale/customer_list.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);

		$this->response->setOutput($this->render());
	}
	//Function report Sales for system
	public function getListSales() {
		$this->language->load('sale/customer');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('sale/customer');

		if (isset($this->request->get['filter_date_start'])) {
			$filter_date_start = $this->request->get['filter_date_start'];
		} else {
			$filter_date_start = null;
		}

		if (isset($this->request->get['filter_date_end'])) {
			$filter_date_end = $this->request->get['filter_date_end'];
		} else {
			$filter_date_end = null;
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$url = '';


		if (isset($this->request->get['filter_date_start'])) {
			$url .= '&filter_date_start=' . urlencode(html_entity_decode($this->request->get['filter_date_start'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_date_end'])) {
			$url .= '&filter_date_end=' . urlencode(html_entity_decode($this->request->get['filter_date_end'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
			'separator' => false
		);

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'),
			'separator' => ' :: '
		);
		//todo
		$this->data['insert'] = $this->url->link('sale/customer/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
		//$this->data['insert'] = $this->url->link('sale/customer/updateNhanhAfterRecieve', 'token=' . $this->session->data['token'] . $url, 'SSL');

		$this->data['customers'] = array();

		$data = array(
			'filter_date_start'        => $filter_date_start,
			'filter_date_end'          => $filter_date_end,
			'start'                    => ($page - 1) * $this->config->get('config_admin_limit'),
			'limit'                    => $this->config->get('config_admin_limit')
		);

		$customer_total = $this->model_sale_customer->getTotalCustomers($data);

		$results = $this->model_sale_customer->getCustomers($data);
		foreach ($results as $result) {
			$color_level = $this->config->get('config_color_level'.$result['level1']);
			if((int)$result['level1'] == 0){
				$level = 'Đại lý';
			}elseif((int)$result['level1'] == 1 || (int)$result['level1'] == 2 || (int)$result['level1'] == 3 || (int)$result['level1'] == 4){
				$level = 'Quản Lý ' . (int)$result['level1'];
			} elseif ((int)$result['level1'] == 5) {
				$level = 'Quản lý Pro';
			} else {
				$level = ' Cổ đông Cty';
			}
			$price2 = $this->model_sale_customer->getHistoriesPrice2($result['customer_id']);
			$customer_parent_info = $this->model_sale_customer->getCustomerForHH($result['customer_parent']);
			$this->data['customers'][] = array(
				'customer_id'    => $result['customer_id'],
				'madn'           => $result['madn'],
				'name'           => $result['name'],
				'price'          =>  $this->currency->format($result['price']),
				'level'          => $level,
				'color_level'    => $color_level,
				'status_id'      => $result['status'],
				'price2'         => $price2 ?  $this->currency->format($price2['price']) : 0,
				'parent'         => $customer_parent_info ? $customer_parent_info['madn'] : '',
				'status'         => ($result['status'] ? 'Đã kích hoạt' : 'Chưa kích hoạt'),
				'date_added'     => date($this->language->get('date_format_short'), strtotime($result['date_added']))
			);
		}
		//Get Total Price and HH
		//////////////////////////////////////////////////////////
		////////////////////////////////////////////////////////////
		$total1 = $this->model_sale_customer->getTotalPrice1($data);
		$this->data['total1'] = $this->currency->format($total1);

		$total2 = $this->model_sale_customer->getTotalPrice2($data);
		$this->data['total2'] = $this->currency->format($total2);

		$this->data['total'] = $this->currency->format($total1 + $total2);
		$this->data['hoahongtt'] =  $this->currency->format((int)$this->model_sale_customer->getTotalHHPriceTrucTiep($data));
		$this->data['hoahonggt'] =  $this->currency->format((int)$this->model_sale_customer->getTotalHHPriceGianTiep($data));

		$this->data['heading_title'] = $this->language->get('heading_title');

		$this->data['text_enabled'] = $this->language->get('text_enabled');
		$this->data['text_disabled'] = $this->language->get('text_disabled');
		$this->data['text_yes'] = $this->language->get('text_yes');
		$this->data['text_no'] = $this->language->get('text_no');
		$this->data['text_select'] = $this->language->get('text_select');
		$this->data['text_default'] = $this->language->get('text_default');
		$this->data['text_no_results'] = $this->language->get('text_no_results');

		$this->data['column_name'] = $this->language->get('column_name');
		$this->data['column_email'] = $this->language->get('column_email');
		$this->data['column_customer_group'] = $this->language->get('column_customer_group');
		$this->data['column_status'] = $this->language->get('column_status');
		$this->data['column_approved'] = $this->language->get('column_approved');
		$this->data['column_ip'] = $this->language->get('column_ip');
		$this->data['column_date_added'] = $this->language->get('column_date_added');
		$this->data['column_login'] = $this->language->get('column_login');
		$this->data['column_action'] = $this->language->get('column_action');

		$this->data['button_approve'] = $this->language->get('button_approve');
		$this->data['button_insert'] = $this->language->get('button_insert');
		$this->data['button_delete'] = $this->language->get('button_delete');
		$this->data['button_filter'] = $this->language->get('button_filter');

		$this->data['token'] = $this->session->data['token'];

		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}

		$url = '';

		if (isset($this->request->get['filter_date_start'])) {
			$url .= '&filter_date_start=' . urlencode(html_entity_decode($this->request->get['filter_date_start'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_date_end'])) {
			$url .= '&filter_date_end=' . urlencode(html_entity_decode($this->request->get['filter_date_end'], ENT_QUOTES, 'UTF-8'));
		}

		$pagination = new Pagination();
		$pagination->total = $customer_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_admin_limit');
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('sale/customer/getListSales', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

		$this->data['pagination'] = $pagination->render();

		$this->data['filter_date_start'] = $filter_date_start;
		$this->data['filter_date_end'] = $filter_date_end;
		$this->template = 'sale/customer_list_sales.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);

		$this->response->setOutput($this->render());
	}

	public function getListHoaHong() {
		$this->language->load('sale/customer');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('sale/customer');

		if (isset($this->request->get['filter_date_start'])) {
			$filter_date_start = $this->request->get['filter_date_start'];
		} else {
			$filter_date_start = null;
		}

		if (isset($this->request->get['filter_date_end'])) {
			$filter_date_end = $this->request->get['filter_date_end'];
		} else {
			$filter_date_end = null;
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$url = '';


		if (isset($this->request->get['filter_date_start'])) {
			$url .= '&filter_date_start=' . urlencode(html_entity_decode($this->request->get['filter_date_start'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_date_end'])) {
			$url .= '&filter_date_end=' . urlencode(html_entity_decode($this->request->get['filter_date_end'], ENT_QUOTES, 'UTF-8'));
		}

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
			'separator' => false
		);

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'),
			'separator' => ' :: '
		);

		$this->data['insert'] = $this->url->link('sale/customer/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');

		$this->data['customers'] = array();

		$data = array(
			'filter_date_start'        => $filter_date_start,
			'filter_date_end'          => $filter_date_end
		);
		$this->data['customers'] = array();
		$check_exist_customer = $this->model_sale_customer->checkExistCustomer($data);
		if($check_exist_customer){
			foreach ($check_exist_customer as $result) {
				$results = $this->model_sale_customer->getCustomer($result);
				if($results){
				// hoa hồng trực tiếp
				$results1 = $this->model_sale_customer->getAllhhBaotro($results['customer_id'],$data);
				// hoa hồng gián tiếp
				$results2 = $this->model_sale_customer->gethhTuvan($results['customer_id'],$data);
				//print_r($results1);
				//print_r($results2);
				$totalnhan = 0;
				$totalchuanhan = 0;

				// hoa hồng trực tiếp
				if($results1){
					foreach($results1 as $result){

						if((int)$result['status'] == 1 ){
							$totalnhan+= $result['price'];
						} else {
							$totalchuanhan+= $result['price'];
						}

					}
				}

				if($results2){
					foreach($results2 as $result){	if((int)$result['status'] == 1 ){
							$totalnhan+= $result['price'];
						} else {
							$totalchuanhan+= $result['price'];
						}
					}
				}
				if((int)$results['level1'] == 0){
					$level = 'Đại lý';
				}elseif((int)$results['level1'] == 1 || (int)$results['level1'] == 2 || (int)$results['level1'] == 3 || (int)$results['level1'] == 4){
					$level = 'Quản Lý ' . (int)$results['level1'];
				} elseif ((int)$results['level1'] == 5) {
					$level = 'Quản lý Pro';
				} else {
					$level = ' Cổ đông Cty';
				}
				// Customer
				$this->data['customers'][] = array(
					'madn' => $results['madn'],
					'name' => $results['name'],
					'level'=> $level,
					'totalnhan' => $this->currency->format($totalnhan),
					'totalchuanhan' => $this->currency->format($totalchuanhan)
				);
			}
		}
		}

		$this->data['heading_title'] = $this->language->get('heading_title');

		$this->data['text_enabled'] = $this->language->get('text_enabled');
		$this->data['text_disabled'] = $this->language->get('text_disabled');
		$this->data['text_yes'] = $this->language->get('text_yes');
		$this->data['text_no'] = $this->language->get('text_no');
		$this->data['text_select'] = $this->language->get('text_select');
		$this->data['text_default'] = $this->language->get('text_default');
		$this->data['text_no_results'] = $this->language->get('text_no_results');

		$this->data['column_name'] = $this->language->get('column_name');
		$this->data['column_email'] = $this->language->get('column_email');
		$this->data['column_customer_group'] = $this->language->get('column_customer_group');
		$this->data['column_status'] = $this->language->get('column_status');
		$this->data['column_approved'] = $this->language->get('column_approved');
		$this->data['column_ip'] = $this->language->get('column_ip');
		$this->data['column_date_added'] = $this->language->get('column_date_added');
		$this->data['column_login'] = $this->language->get('column_login');
		$this->data['column_action'] = $this->language->get('column_action');

		$this->data['button_approve'] = $this->language->get('button_approve');
		$this->data['button_insert'] = $this->language->get('button_insert');
		$this->data['button_delete'] = $this->language->get('button_delete');
		$this->data['button_filter'] = $this->language->get('button_filter');

		$this->data['token'] = $this->session->data['token'];

		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}

		$url = '';

		if (isset($this->request->get['filter_date_start'])) {
			$url .= '&filter_date_start=' . urlencode(html_entity_decode($this->request->get['filter_date_start'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_date_end'])) {
			$url .= '&filter_date_end=' . urlencode(html_entity_decode($this->request->get['filter_date_end'], ENT_QUOTES, 'UTF-8'));
		}

		$this->data['filter_date_start'] = $filter_date_start;
		$this->data['filter_date_end'] = $filter_date_end;
		$this->template = 'sale/customer_list_hoahong.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);

		$this->response->setOutput($this->render());
	}

	protected function getForm() {
		$this->data['heading_title'] = $this->language->get('heading_title');

		$this->data['text_enabled'] = $this->language->get('text_enabled');
		$this->data['text_disabled'] = $this->language->get('text_disabled');
		$this->data['text_select'] = $this->language->get('text_select');
		$this->data['text_none'] = $this->language->get('text_none');
		$this->data['text_wait'] = $this->language->get('text_wait');
		$this->data['text_no_results'] = $this->language->get('text_no_results');
		$this->data['text_add_ban_ip'] = $this->language->get('text_add_ban_ip');
		$this->data['text_remove_ban_ip'] = $this->language->get('text_remove_ban_ip');

		$this->data['column_ip'] = $this->language->get('column_ip');
		$this->data['column_total'] = $this->language->get('column_total');
		$this->data['column_date_added'] = $this->language->get('column_date_added');
		$this->data['column_action'] = $this->language->get('column_action');

		$this->data['entry_firstname'] = $this->language->get('entry_firstname');
		$this->data['entry_lastname'] = $this->language->get('entry_lastname');
		$this->data['entry_email'] = $this->language->get('entry_email');
		$this->data['entry_telephone'] = $this->language->get('entry_telephone');
		$this->data['entry_fax'] = $this->language->get('entry_fax');
		$this->data['entry_password'] = $this->language->get('entry_password');
		$this->data['entry_confirm'] = $this->language->get('entry_confirm');
		$this->data['entry_newsletter'] = $this->language->get('entry_newsletter');
		$this->data['entry_customer_group'] = $this->language->get('entry_customer_group');
		$this->data['entry_status'] = $this->language->get('entry_status');
		$this->data['entry_company'] = $this->language->get('entry_company');
		$this->data['entry_company_id'] = $this->language->get('entry_company_id');
		$this->data['entry_tax_id'] = $this->language->get('entry_tax_id');
		$this->data['entry_address_1'] = $this->language->get('entry_address_1');
		$this->data['entry_address_2'] = $this->language->get('entry_address_2');
		$this->data['entry_city'] = $this->language->get('entry_city');
		$this->data['entry_postcode'] = $this->language->get('entry_postcode');
		$this->data['entry_zone'] = $this->language->get('entry_zone');
		$this->data['entry_country'] = $this->language->get('entry_country');
		$this->data['entry_default'] = $this->language->get('entry_default');
		$this->data['entry_comment'] = $this->language->get('entry_comment');
		$this->data['entry_description'] = $this->language->get('entry_description');
		$this->data['entry_amount'] = $this->language->get('entry_amount');
		$this->data['entry_points'] = $this->language->get('entry_points');

		$this->data['button_save'] = $this->language->get('button_save');
		$this->data['button_cancel'] = $this->language->get('button_cancel');
		$this->data['button_add_address'] = $this->language->get('button_add_address');
		$this->data['button_add_history'] = $this->language->get('button_add_history');
		$this->data['button_add_transaction'] = $this->language->get('button_add_transaction');
		$this->data['button_add_reward'] = $this->language->get('button_add_reward');
		$this->data['button_remove'] = $this->language->get('button_remove');

		$this->data['tab_general'] = $this->language->get('tab_general');
		$this->data['tab_address'] = $this->language->get('tab_address');
		$this->data['tab_history'] = $this->language->get('tab_history');
		$this->data['tab_transaction'] = $this->language->get('tab_transaction');
		$this->data['tab_reward'] = $this->language->get('tab_reward');
		$this->data['tab_ip'] = $this->language->get('tab_ip');

		$this->data['token'] = $this->session->data['token'];

		if (isset($this->request->get['customer_id'])) {
			$this->data['customer_id'] = $this->request->get['customer_id'];
		} else {
			$this->data['customer_id'] = 0;
		}

		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}

		if (isset($this->error['name'])) {
			$this->data['error_name'] = $this->error['name'];
		} else {
			$this->data['error_name'] = '';
		}

		if (isset($this->error['email'])) {
			$this->data['error_email'] = $this->error['email'];
		} else {
			$this->data['error_email'] = '';
		}

		if (isset($this->error['customer'])) {
			$this->data['error_customer'] = $this->error['customer'];
		} else {
			$this->data['error_customer'] = '';
		}

		if (isset($this->error['madn'])) {
			$this->data['error_madn'] = $this->error['madn'];
		} else {
			$this->data['error_madn'] = '';
		}

		if (isset($this->error['price'])) {
			$this->data['error_price'] = $this->error['price'];
		} else {
			$this->data['error_price'] = '';
		}

		if (isset($this->error['password'])) {
			$this->data['error_password'] = $this->error['password'];
		} else {
			$this->data['error_password'] = '';
		}

		if (isset($this->error['confirm'])) {
			$this->data['error_confirm'] = $this->error['confirm'];
		} else {
			$this->data['error_confirm'] = '';
		}
		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_email'])) {
			$url .= '&filter_email=' . urlencode(html_entity_decode($this->request->get['filter_email'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['filter_date_added'])) {
			$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
			'separator' => false
		);

		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL'),
			'separator' => ' :: '
		);

		if (!isset($this->request->get['customer_id'])) {
			$this->data['action'] = $this->url->link('sale/customer/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
			//$this->data['action'] = $this->url->link('sale/customer/updateNhanhAfterRecieve', 'token=' . $this->session->data['token'] . $url, 'SSL');
		} else {
			$this->data['action_update'] = $this->url->link('sale/customer/updatePrice', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . $url, 'SSL');
			$this->data['action'] = $this->url->link('sale/customer/update', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . $url, 'SSL');
		}

		$this->data['cancel'] = $this->url->link('sale/customer', 'token=' . $this->session->data['token'] . $url, 'SSL');
		if (isset($this->request->get['customer_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
			$customer_info = $this->model_sale_customer->getCustomer($this->request->get['customer_id']);

		}

		if (isset($this->request->post['name'])) {
			$this->data['name'] = $this->request->post['name'];
		} elseif (!empty($customer_info)) {
			$this->data['name'] = $customer_info['name'];
		} else {
			$this->data['name'] = '';
		}

		if (isset($this->request->post['email'])) {
			$this->data['email'] = $this->request->post['email'];
		} elseif (!empty($customer_info)) {
			$this->data['email'] = $customer_info['email'];
		} else {
			$this->data['email'] = '';
		}

		if (isset($this->request->post['bank'])) {
			$this->data['bank'] = $this->request->post['bank'];
		} elseif (!empty($customer_info)) {
			$this->data['bank'] = $customer_info['bank'];
		} else {
			$this->data['bank'] = '';
		}

		if (isset($this->request->post['telephone'])) {
			$this->data['telephone'] = $this->request->post['telephone'];
		} elseif (!empty($customer_info)) {
			$this->data['telephone'] = $customer_info['telephone'];
		} else {
			$this->data['telephone'] = '';
		}

		if (isset($this->request->post['customer'])) {
			$this->data['customer'] = $this->request->post['customer'];
		} elseif (!empty($customer_info)) {
			$customer_parent_info = $this->model_sale_customer->getCustomerForHH($customer_info['customer_parent']);
			$this->data['customer'] = $customer_parent_info ? $customer_parent_info['madn'] : NULL;
		} else {
			$this->data['customer'] = '';
		}
       // print_r($this->data['customer']);exit;
		if (isset($this->request->post['madn'])) {
			$this->data['madn'] = $this->request->post['madn'];
		} elseif (!empty($customer_info)) {
			$this->data['madn'] = $customer_info['madn'];
		} else {
			$this->data['madn'] = '';
		}

		if (isset($this->request->post['magioithieu'])) {
			$this->data['magioithieu'] = $this->request->post['magioithieu'];
		} elseif (!empty($customer_info)) {
			$this->data['magioithieu'] = $customer_info['machidinh'];
		} else {
			$this->data['magioithieu'] = '';
		}

		if (isset($this->request->post['customer'])) {
			$this->data['customer'] = $this->request->post['customer'];
		} elseif (!empty($customer_info)) {
			$customer_info_parent =  $this->model_sale_customer->getCustomerForHH($customer_info['machidinh']);
			if(!empty($customer_info_parent)){
				$this->data['customer'] = $customer_info_parent['madn'];
			} else {
				$this->data['customer'] = '';
			}
		} else {
			$this->data['customer'] = '';
		}
		//Them ma chi dinh
		if (isset($this->request->post['machidinh'])) {
			$this->data['machidinh'] = $this->request->post['machidinh'];
		} elseif (!empty($customer_info)) {
			$this->data['machidinh'] = $customer_info['customer_parent'];
		} else {
			$this->data['machidinh'] = '';
		}

		if (isset($this->request->post['customer_chidinh'])) {
			$this->data['customer_chidinh'] = $this->request->post['customer_chidinh'];
		} elseif (!empty($customer_info)) {
			$customer_info_parent =  $this->model_sale_customer->getCustomerForHH($customer_info['customer_parent']);
			if(!empty($customer_info_parent)){
				$this->data['customer_chidinh'] = $customer_info_parent['madn'];
			} else {
				$this->data['customer_chidinh'] = '';
			}
		} else {
			$this->data['customer_chidinh'] = '';
		}

		if (isset($this->request->post['price'])) {
			$this->data['price'] = $this->request->post['price'];
		} elseif (!empty($customer_info)) {
			$this->data['price'] = $customer_info['price'];
		} else {
			$this->data['price'] = $this->config->get('config_price');
		}

		if (!empty($customer_info)) {
			$this->data['date_added'] = date('Y-m-d', strtotime($customer_info['date_added']));
		} else {
			$this->data['date_added'] ='';
		}

		if (isset($this->request->post['born'])) {
			$this->data['born'] = $this->request->post['born'];
		} elseif (!empty($customer_info)) {
			$this->data['born'] = $customer_info['born'];
		} else {
			$this->data['born'] = '';
		}

		if (isset($this->request->post['address'])) {
			$this->data['address'] = $this->request->post['address'];
		} elseif (!empty($customer_info)) {
			$this->data['address'] = $customer_info['address'];
		} else {
			$this->data['address'] = '';
		}

		if (isset($this->request->post['status'])) {
			$this->data['status'] = $this->request->post['status'];
		} elseif (!empty($customer_info)) {
			$this->data['status'] = $customer_info['status'];
		} else {
			$this->data['status'] = 0;
		}

		if (isset($this->request->post['password'])) {
			$this->data['password'] = $this->request->post['password'];
		} else {
			$this->data['password'] = '';
		}

		if (isset($this->request->post['confirm'])) {
			$this->data['confirm'] = $this->request->post['confirm'];
		} else {
			$this->data['confirm'] = '';
		}
		//Get getHistoriesPrice2
		$this->data['history'] = array();
		if(isset($this->request->get['customer_id'])){
			$this->data['history'] = $this->model_sale_customer->getHistoriesPrice2($this->request->get['customer_id']) ? $this->model_sale_customer->getHistoriesPrice2($this->request->get['customer_id']) : NULL;
			if($this->data['history']){
				$this->data['history']['price'] = $this->currency->format($this->data['history']['price']);
				$this->data['history']['date_added'] =  date('Y-m-d', strtotime($this->data['history']['date_added']));
			}
		}
		$this->data['transaction'] = array();
		$this->data['total'] = 0;
		if(isset($this->request->get['customer_id'])){
			$transaction = $this->model_sale_customer->getTransactions($data = array('customer_id' => $this->request->get['customer_id']));
			if($transaction){
				foreach($transaction as $value){
					$this->data['total'] += $value['price'];
					$this->data['transaction'][] = array(
						'price'      => $this->currency->format($value['price']),
						'date_added' => date('Y-m-d', strtotime($value['date_added'])),
						'comment'    => $value['comment']
					);
				}
			}
		}
		$this->data['total'] = $this->currency->format($this->data['total']);
		$this->data['config_price'] = $this->config->get('config_price');
		$this->template = 'sale/customer_form.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);

		$this->response->setOutput($this->render());
	}

	protected function validateForm() {
		if (!$this->user->hasPermission('modify', 'sale/customer')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		if ((utf8_strlen($this->request->post['name']) < 1) || (utf8_strlen($this->request->post['name']) > 32)) {
			$this->error['name'] = 'Tên không được để trống';
		}

		if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email'])) {
			$this->error['email'] = $this->language->get('error_email');
		}
		if($this->user->getGroup() != 1){
			if (!isset($this->request->get['customer_id'])) {
				if ((int)$this->request->post['price'] <= 0){
					$this->error['price'] = 'Tiền đăng ký phải được nhập';
				}
			}
		}
		$customer_info = $this->model_sale_customer->getCustomerByMaDN($this->request->post['madn']);
		if($customer_info){
			$this->error['madn'] = 'Mã đăng nhập đã tồn tại trong hệ thống';
		}
		if(utf8_strlen($this->request->post['madn']) < 3){
			$this->error['madn'] = 'Mã đăng nhập phải dài hơn 3 ký tự';
		}
		if($this->user->getGroup() != 1){
			if(!$this->request->post['magioithieu']){
				$this->error['customer'] = 'Mã người giới thiệu không để trống';
			}
		}
		if ($this->request->post['password'] || (!isset($this->request->get['customer_id']))) {
			if ((utf8_strlen($this->request->post['password']) < 4) || (utf8_strlen($this->request->post['password']) > 20)) {
				$this->error['password'] = $this->language->get('error_password');
			}

			if ($this->request->post['password'] != $this->request->post['confirm']) {
				$this->error['confirm'] = $this->language->get('error_confirm');
			}
		}

		if ($this->error && !isset($this->error['warning'])) {
			$this->error['warning'] = $this->language->get('error_warning');
		}

		if (!$this->error) {
			return true;
		} else {
			return false;
		}
	}

	protected function validateDelete() {
		if (!$this->user->hasPermission('modify', 'sale/customer')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		if (!$this->error) {
			return true;
		} else {
			return false;
		}
	}

	public function login() {
		$json = array();

		if (isset($this->request->get['customer_id'])) {
			$customer_id = $this->request->get['customer_id'];
		} else {
			$customer_id = 0;
		}

		$this->load->model('sale/customer');

		$customer_info = $this->model_sale_customer->getCustomer($customer_id);

		if ($customer_info) {
			$token = md5(mt_rand());

			$this->model_sale_customer->editToken($customer_id, $token);

			if (isset($this->request->get['store_id'])) {
				$store_id = $this->request->get['store_id'];
			} else {
				$store_id = 0;
			}

			$this->load->model('setting/store');

			$store_info = $this->model_setting_store->getStore($store_id);

			if ($store_info) {
				$this->redirect($store_info['url'] . 'index.php?route=account/login&token=' . $token);
			} else {
				$this->redirect(HTTP_CATALOG . 'index.php?route=account/login&token=' . $token);
			}
		} else {
			$this->language->load('error/not_found');

			$this->document->setTitle($this->language->get('heading_title'));

			$this->data['heading_title'] = $this->language->get('heading_title');

			$this->data['text_not_found'] = $this->language->get('text_not_found');

			$this->data['breadcrumbs'] = array();

			$this->data['breadcrumbs'][] = array(
				'text'      => $this->language->get('text_home'),
				'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
				'separator' => false
			);

			$this->data['breadcrumbs'][] = array(
				'text'      => $this->language->get('heading_title'),
				'href'      => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL'),
				'separator' => ' :: '
			);

			$this->template = 'error/not_found.tpl';
			$this->children = array(
				'common/header',
				'common/footer'
			);

			$this->response->setOutput($this->render());
		}
	}

	public function history() {
		$this->language->load('sale/customer');

		$this->load->model('sale/customer');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->user->hasPermission('modify', 'sale/customer')) {
			$this->model_sale_customer->addHistory($this->request->get['customer_id'], $this->request->post['comment']);

			$this->data['success'] = $this->language->get('text_success');
		} else {
			$this->data['success'] = '';
		}

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && !$this->user->hasPermission('modify', 'sale/customer')) {
			$this->data['error_warning'] = $this->language->get('error_permission');
		} else {
			$this->data['error_warning'] = '';
		}

		$this->data['text_no_results'] = $this->language->get('text_no_results');

		$this->data['column_date_added'] = $this->language->get('column_date_added');
		$this->data['column_comment'] = $this->language->get('column_comment');

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$this->data['histories'] = array();

		$results = $this->model_sale_customer->getHistories($this->request->get['customer_id'], ($page - 1) * 10, 10);

		foreach ($results as $result) {
			$this->data['histories'][] = array(
				'comment'     => $result['comment'],
				'date_added'  => date($this->language->get('date_format_short'), strtotime($result['date_added']))
			);
		}

		$transaction_total = $this->model_sale_customer->getTotalHistories($this->request->get['customer_id']);

		$pagination = new Pagination();
		$pagination->total = $transaction_total;
		$pagination->page = $page;
		$pagination->limit = 10;
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('sale/customer/history', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL');

		$this->data['pagination'] = $pagination->render();

		$this->template = 'sale/customer_history.tpl';

		$this->response->setOutput($this->render());
	}

	public function transaction() {
		$this->language->load('sale/customer');

		$this->load->model('sale/customer');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->user->hasPermission('modify', 'sale/customer')) {
			$this->model_sale_customer->addTransaction($this->request->get['customer_id'], $this->request->post['description'], $this->request->post['amount']);

			$this->data['success'] = $this->language->get('text_success');
		} else {
			$this->data['success'] = '';
		}

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && !$this->user->hasPermission('modify', 'sale/customer')) {
			$this->data['error_warning'] = $this->language->get('error_permission');
		} else {
			$this->data['error_warning'] = '';
		}

		$this->data['text_no_results'] = $this->language->get('text_no_results');
		$this->data['text_balance'] = $this->language->get('text_balance');

		$this->data['column_date_added'] = $this->language->get('column_date_added');
		$this->data['column_description'] = $this->language->get('column_description');
		$this->data['column_amount'] = $this->language->get('column_amount');

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$this->data['transactions'] = array();

		$results = $this->model_sale_customer->getTransactions($this->request->get['customer_id'], ($page - 1) * 10, 10);

		foreach ($results as $result) {
			$this->data['transactions'][] = array(
				'amount'      => $this->currency->format($result['amount'], $this->config->get('config_currency')),
				'description' => $result['description'],
				'date_added'  => date($this->language->get('date_format_short'), strtotime($result['date_added']))
			);
		}

		$this->data['balance'] = $this->currency->format($this->model_sale_customer->getTransactionTotal($this->request->get['customer_id']), $this->config->get('config_currency'));

		$transaction_total = $this->model_sale_customer->getTotalTransactions($this->request->get['customer_id']);

		$pagination = new Pagination();
		$pagination->total = $transaction_total;
		$pagination->page = $page;
		$pagination->limit = 10;
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('sale/customer/transaction', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL');

		$this->data['pagination'] = $pagination->render();

		$this->template = 'sale/customer_transaction.tpl';

		$this->response->setOutput($this->render());
	}

	public function reward() {
		$this->language->load('sale/customer');

		$this->load->model('sale/customer');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->user->hasPermission('modify', 'sale/customer')) {
			$this->model_sale_customer->addReward($this->request->get['customer_id'], $this->request->post['description'], $this->request->post['points']);

			$this->data['success'] = $this->language->get('text_success');
		} else {
			$this->data['success'] = '';
		}

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && !$this->user->hasPermission('modify', 'sale/customer')) {
			$this->data['error_warning'] = $this->language->get('error_permission');
		} else {
			$this->data['error_warning'] = '';
		}

		$this->data['text_no_results'] = $this->language->get('text_no_results');
		$this->data['text_balance'] = $this->language->get('text_balance');

		$this->data['column_date_added'] = $this->language->get('column_date_added');
		$this->data['column_description'] = $this->language->get('column_description');
		$this->data['column_points'] = $this->language->get('column_points');

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$this->data['rewards'] = array();

		$results = $this->model_sale_customer->getRewards($this->request->get['customer_id'], ($page - 1) * 10, 10);

		foreach ($results as $result) {
			$this->data['rewards'][] = array(
				'points'      => $result['points'],
				'description' => $result['description'],
				'date_added'  => date($this->language->get('date_format_short'), strtotime($result['date_added']))
			);
		}

		$this->data['balance'] = $this->model_sale_customer->getRewardTotal($this->request->get['customer_id']);

		$reward_total = $this->model_sale_customer->getTotalRewards($this->request->get['customer_id']);

		$pagination = new Pagination();
		$pagination->total = $reward_total;
		$pagination->page = $page;
		$pagination->limit = 10;
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('sale/customer/reward', 'token=' . $this->session->data['token'] . '&customer_id=' . $this->request->get['customer_id'] . '&page={page}', 'SSL');

		$this->data['pagination'] = $pagination->render();

		$this->template = 'sale/customer_reward.tpl';

		$this->response->setOutput($this->render());
	}

	public function addBanIP() {
		$this->language->load('sale/customer');

		$json = array();

		if (isset($this->request->post['ip'])) {
			if (!$this->user->hasPermission('modify', 'sale/customer')) {
				$json['error'] = $this->language->get('error_permission');
			} else {
				$this->load->model('sale/customer');

				$this->model_sale_customer->addBanIP($this->request->post['ip']);

				$json['success'] = $this->language->get('text_success');
			}
		}

		$this->response->setOutput(json_encode($json));
	}

	public function removeBanIP() {
		$this->language->load('sale/customer');

		$json = array();

		if (isset($this->request->post['ip'])) {
			if (!$this->user->hasPermission('modify', 'sale/customer')) {
				$json['error'] = $this->language->get('error_permission');
			} else {
				$this->load->model('sale/customer');

				$this->model_sale_customer->removeBanIP($this->request->post['ip']);

				$json['success'] = $this->language->get('text_success');
			}
		}

		$this->response->setOutput(json_encode($json));
	}

	public function autocomplete() {
		$json = array();

		if (isset($this->request->get['filter_name'])) {
			$this->load->model('sale/customer');

			$data = array(
				'filter_name' => $this->request->get['filter_name'],
				'start'       => 0,
				'limit'       => 20
			);

			$results = $this->model_sale_customer->getCustomers($data);

			foreach ($results as $result) {
				$json[] = array(
					'customer_id'       => $result['customer_id'],
					'customer_group_id' => $result['customer_group_id'],
					'name'              => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
					'customer_group'    => $result['customer_group'],
					'firstname'         => $result['firstname'],
					'lastname'          => $result['lastname'],
					'email'             => $result['email'],
					'telephone'         => $result['telephone'],
					'fax'               => $result['fax'],
					'address'           => $this->model_sale_customer->getAddresses($result['customer_id'])
				);
			}
		}

		$sort_order = array();

		foreach ($json as $key => $value) {
			$sort_order[$key] = $value['name'];
		}

		array_multisort($sort_order, SORT_ASC, $json);

		$this->response->setOutput(json_encode($json));
	}
	public function autocompleteCustomer() {
		$json = array();

		if (isset($this->request->get['filter_customer'])) {
			$this->load->model('sale/customer');
			if(isset($this->request->get['type']) && $this->request->get['type']) {$type = 1;} else {$type = 0; }
			$data = array(
				'filter_customer' => $this->request->get['filter_customer'],
				'start'       => 0,
				'type'       => $type,
				'limit'       => 20
			);

			$results = $this->model_sale_customer->getCustomers($data);

			foreach ($results as $result) {
				$json[] = array(
					'customer_id'       => $result['customer_id'],
					'madn'       => $result['madn']
				);
			}
		}

		$sort_order = array();

		foreach ($json as $key => $value) {
			$sort_order[$key] = $value['customer_id'];
		}

		array_multisort($sort_order, SORT_ASC, $json);

		$this->response->setOutput(json_encode($json));
	}

	public function country() {
		$json = array();

		$this->load->model('localisation/country');

		$country_info = $this->model_localisation_country->getCountry($this->request->get['country_id']);

		if ($country_info) {
			$this->load->model('localisation/zone');

			$json = array(
				'country_id'        => $country_info['country_id'],
				'name'              => $country_info['name'],
				'iso_code_2'        => $country_info['iso_code_2'],
				'iso_code_3'        => $country_info['iso_code_3'],
				'address_format'    => $country_info['address_format'],
				'postcode_required' => $country_info['postcode_required'],
				'zone'              => $this->model_localisation_zone->getZonesByCountryId($this->request->get['country_id']),
				'status'            => $country_info['status']
			);
		}

		$this->response->setOutput(json_encode($json));
	}

	public function address() {
		$json = array();

		if (!empty($this->request->get['address_id'])) {
			$this->load->model('sale/customer');

			$json = $this->model_sale_customer->getAddress($this->request->get['address_id']);
		}

		$this->response->setOutput(json_encode($json));
	}
	//Thu tien lan 2
	public function updatePrice() {
		if ($this->request->server['REQUEST_METHOD'] == 'POST'){
			$this->load->model('sale/customer');
			$this->model_sale_customer->updatePrice($this->request->get['customer_id'],$this->request->post);
			//function cập nhập hoa hồng trực tiếp và hoa hồng gián tiếp cho customer
			$customer_info = $this->model_sale_customer->getCustomer($this->request->get['customer_id']);

			$this->addHoaHongTrucTiep($this->request->get['customer_id'],$customer_info['customer_parent'],$this->config->get('config_hh_tructiep'));

			$this->addHoaHongGianTiep($this->request->get['customer_id'],$customer_info['machidinh'],$this->config->get('config_level'),$this->config->get('config_hh_gian_tiep'))	;

			// Function cập nhập level cho customer trong nhanh

			$this->updateNhanh($customer_info['customer_parent']);

			$this->session->data['success'] = 'Hệ thống đã cập nhập thành công';
			$this->redirect($this->url->link('sale/customer', 'token=' . $this->session->data['token'], 'SSL'));
		}
	}

	// Add function
	public function addHoaHongTrucTiep($customer_id,$customer_parent,$price){
        $data=array();
        $data['customer_id']=$customer_id;
        $data['customer_parent']=$customer_parent;
        $data['price']=$price;
        $this->load->model('sale/customer');
        $this->model_sale_customer->addHoaHongTrucTiep($data);
		//Write function here

	}

	public function addHoaHongGianTiep($customer_id,$customer_parent,$limit,$price){

		//Write function here
       $this->load->model('sale/customer');
       $results=array();

       $results[0]=$this->model_sale_customer->getCustomerForHH($customer_id);
        if(isset($results[0]['machidinh']) && $results[0]['machidinh']!=0){

            for($i=1;$i<($limit);$i++){
                $j=$i-1;

                if(isset($results[$j]['machidinh']) && ($results[$j]['machidinh']!=0)){
                $results[$i]=$this->model_sale_customer->getCustomer($results[$j]['machidinh']);
                if(isset($results[$i]['machidinh']) && ($results[$i]['machidinh']!=0)){
               // var_dump($results[$i]);
                    $this->model_sale_customer->addHoaHongGianTiep($customer_id,$results[$i]['machidinh'],$price);

                }
				}
            }
        }
       //var_dump($results);
       //die;

	}

	// Function cập nhập level cho customer trong nhanh

	//code's Vy
     public function updateNhanh1($customer_id){
	//Input: customer_id of parent.
        $customer_info = $this->model_sale_customer->getCustomer($customer_id);
		//Update level for customer
        if($customer_info){
			//Gia tri cho thanh vien
            $level = $customer_info['level1'];
            $value_index = $customer_info['index_value1'];
			$level_childen = $customer_info['level_childen'];

			//Gia tri de update cho nhanh.
			$level_nhanh = $customer_info['level2'];
            $value_index_nhanh = $customer_info['index_value2'];
            $level_childen_nhanh = $customer_info['level_childen_nhanh'];
//          if($level_childen != null) $datas_level = unserialize($level_nhanh);
//           if($level_childen_nhanh !=null) $data_level_nhanh = unserialize($level_childen_nhanh);
			//Cap nhap level_childen cho parent

            if($level == 0){
                if($value_index == 49) {
                    $this->model_sale_customer->updateLevelCustomer($customer_id,$level+1);
                    if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']){
                        $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                        if($customer_pr_info['level_childen']){
                            $level_child_datas=unserialize($customer_pr_info['level_childen']);
                        }
						if(!isset($level_child_datas[$customer_id])){
							$level_child_datas[$customer_id] = '1';
							$this->model_sale_customer->updateLevelChilden($customer_info['customer_parent'],serialize($level_child_datas));
						}
/* 						if(isset($level_child_datas[$customer_id])){$a = $level_child_datas[$customer_id]
							if($
						} else {
							$level_child_datas[$customer_id] = '1';
						} */
                       // var_dump($level_child_datas);
                      /*  if(isset($level_child_datas) && $level_child_datas){

                            foreach($level_child_datas as $key => $value){
                                if($key==$customer_id){
/* 									$array_values = explode(':',$value)
									foreach($array_values as $array_value){
										if($array_value!=){

										}
										//$temp = array('id'=>$customer_id,'level'=>array('0'=>1));
										//array_push($level_child_datas,$temp);
									}
                                }
                            }
                        }else{ */
                      //  }
                        //var_dump($level_child_datas);
                        //$temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                    }

            }
            else {
                //
               // if(isset($this->session->data['level_update'][$level])){
                    if($level == 1){
                        if(isset($this->session->data['level_update'][$level])){
                            if($level_childen!=null){
                                $data_childs=unserialize($level_childen);
                                foreach($data_childs as $data_child){
                                    if(in_array(1,$data_child['level']))
                                    $temp=true;
                                    break;
                                }
                                if(($temp)&&($value_index==1)){
                                    $this->model_sale_customer->updateLevelCustomer($customer_id,$level+1);
                                    if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                        $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                        if($customer_pr_info['level_childen']!=null)
                                        {
                                            $level_child_datas=unserialize($customer_pr_info['level_childen']);
                                        }
                                        // var_dump($level_child_datas);
                                        if(isset($level_child_datas)){
                                            foreach($level_child_datas as $data){
                                                if($data['id']!=$customer_id){
                                                    $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                    array_push($level_child_datas,$temp);
                                                }
                                            }
                                        }else{
                                            $level_child_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                        }
                                        $this->model_sale_customer->updateLevelChilden($customer_info['custormer_parent'],serialize($level_child_datas));
                                    }
                                }else{
                                    $this->model_sale_customer->updateIndexValueCustomer($customer_id,$value_index+1);
                                }
                            }
                            else{

                                if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                    $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                    if($customer_pr_info['level_childen']!=null)
                                    {
                                        $level_child_datas=unserialize($customer_pr_info['level_childen']);
                                    }
                                    // var_dump($level_child_datas);
                                    if(isset($level_child_datas)){
                                        foreach($level_child_datas as $data){
                                            if($data['id']!=$customer_id){
                                                $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                array_push($level_child_datas,$temp);
                                            }
                                        }
                                    }else{
                                        $level_child_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                    }
                                    $this->model_sale_customer->updateLevelChilden($customer_info['custormer_parent'],serialize($level_child_datas));

                                }
                                $this->model_sale_customer->updateIndexValueCustomer($customer_id,$value_index+1);
                            }

                        }
                    }elseif($level==2){
                        if(isset($this->session->data['level_update'][$level])){
                            if($level_childen!=null){
                                $data_childs=unserialize($level_childen);
                                foreach($data_childs as $data_child){
                                    if(in_array(1,$data_child['level']))
                                        $temp=true;
                                    break;
                                }
                                if(($temp)&&($value_index==1)){
                                    $this->model_sale_customer->updateLevelCustomer($customer_id,$level+1);
                                    if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                        $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                        if($customer_pr_info['level_childen']!=null)
                                        {
                                            $level_child_datas=unserialize($customer_pr_info['level_childen']);
                                        }
                                        // var_dump($level_child_datas);
                                        if(isset($level_child_datas)){
                                            foreach($level_child_datas as $data){
                                                if($data['id']!=$customer_id){
                                                    $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                    array_push($level_child_datas,$temp);
                                                }
                                            }
                                        }else{
                                            $level_child_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                        }
                                        $this->model_sale_customer->updateLevelChilden($customer_info['custormer_parent'],serialize($level_child_datas));
                                    }
                                }else{
                                    $this->model_sale_customer->updateIndexValueCustomer($customer_id,$value_index+1);
                                }
                            }
                            else{

                                if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                    $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                    if($customer_pr_info['level_childen']!=null)
                                    {
                                        $level_child_datas=unserialize($customer_pr_info['level_childen']);
                                    }
                                    // var_dump($level_child_datas);
                                    if(isset($level_child_datas)){
                                        foreach($level_child_datas as $data){
                                            if($data['id']!=$customer_id){
                                                $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                array_push($level_child_datas,$temp);
                                            }
                                        }
                                    }else{
                                        $level_child_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                    }
                                    $this->model_sale_customer->updateLevelChilden($customer_info['custormer_parent'],serialize($level_child_datas));

                                }
                                $this->model_sale_customer->updateIndexValueCustomer($customer_id,$value_index+1);
                            }

                        }
                    }
                    elseif($level==3) {
						 if(isset($this->session->data['level_update'][$level])){
                            if($level_childen!=null){
                                $data_childs=unserialize($level_childen);
                                foreach($data_childs as $data_child){
                                    if(in_array(1,$data_child['level']))
                                        $temp=true;
                                    break;
                                }
                                if(($temp)&&($value_index==1)){
                                    $this->model_sale_customer->updateLevelCustomer($customer_id,$level+1);
                                    if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                        $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                        if($customer_pr_info['level_childen']!=null)
                                        {
                                            $level_child_datas=unserialize($customer_pr_info['level_childen']);
                                        }
                                        // var_dump($level_child_datas);
                                        if(isset($level_child_datas)){
                                            foreach($level_child_datas as $data){
                                                if($data['id']!=$customer_id){
                                                    $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                    array_push($level_child_datas,$temp);
                                                }
                                            }
                                        }else{
                                            $level_child_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                        }
                                        $this->model_sale_customer->updateLevelChilden($customer_info['custormer_parent'],serialize($level_child_datas));
                                    }
                                }else{
                                    $this->model_sale_customer->updateIndexValueCustomer($customer_id,$value_index+1);
                                }
                            }
                            else{

                                if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                    $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                    if($customer_pr_info['level_childen']!=null)
                                    {
                                        $level_child_datas=unserialize($customer_pr_info['level_childen']);
                                    }
                                    // var_dump($level_child_datas);
                                    if(isset($level_child_datas)){
                                        foreach($level_child_datas as $data){
                                            if($data['id']!=$customer_id){
                                                $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                array_push($level_child_datas,$temp);
                                            }
                                        }
                                    }else{
                                        $level_child_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                    }
                                    $this->model_sale_customer->updateLevelChilden($customer_info['custormer_parent'],serialize($level_child_datas));

                                }
                                $this->model_sale_customer->updateIndexValueCustomer($customer_id,$value_index+1);
                            }

                        }

                    }
                    elseif($level==4){
						 if(isset($this->session->data['level_update'][$level])){
                            if($level_childen!=null){
                                $data_childs=unserialize($level_childen);
                                foreach($data_childs as $data_child){
                                    if(in_array(1,$data_child['level']))
                                        $temp=true;
                                    break;
                                }
                                if(($temp)&&($value_index==1)){
                                    $this->model_sale_customer->updateLevelCustomer($customer_id,$level+1);
                                    if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                        $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                        if($customer_pr_info['level_childen']!=null)
                                        {
                                            $level_child_datas=unserialize($customer_pr_info['level_childen']);
                                        }
                                        // var_dump($level_child_datas);
                                        if(isset($level_child_datas)){
                                            foreach($level_child_datas as $data){
                                                if($data['id']!=$customer_id){
                                                    $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                    array_push($level_child_datas,$temp);
                                                }
                                            }
                                        }else{
                                            $level_child_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                        }
                                        $this->model_sale_customer->updateLevelChilden($customer_info['custormer_parent'],serialize($level_child_datas));
                                    }
                                }else{
                                    $this->model_sale_customer->updateIndexValueCustomer($customer_id,$value_index+1);
                                }
                            }
                            else{

                                if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                    $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                    if($customer_pr_info['level_childen']!=null)
                                    {
                                        $level_child_datas=unserialize($customer_pr_info['level_childen']);
                                    }
                                    // var_dump($level_child_datas);
                                    if(isset($level_child_datas)){
                                        foreach($level_child_datas as $data){
                                            if($data['id']!=$customer_id){
                                                $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                array_push($level_child_datas,$temp);
                                            }
                                        }
                                    }else{
                                        $level_child_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                    }
                                    $this->model_sale_customer->updateLevelChilden($customer_info['custormer_parent'],serialize($level_child_datas));

                                }
                                $this->model_sale_customer->updateIndexValueCustomer($customer_id,$value_index+1);
                            }

                        }
                    }
                    elseif($level==5){
						 if(isset($this->session->data['level_update'][$level])){
                            if($level_childen!=null){
                                $data_childs=unserialize($level_childen);
                                foreach($data_childs as $data_child){
                                    if(in_array(1,$data_child['level']))
                                        $temp=true;
                                    break;
                                }
                                if(($temp)&&($value_index==1)){
                                    $this->model_sale_customer->updateLevelCustomer($customer_id,$level+1);
                                    if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                        $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                        if($customer_pr_info['level_childen']!=null)
                                        {
                                            $level_child_datas=unserialize($customer_pr_info['level_childen']);
                                        }
                                        // var_dump($level_child_datas);
                                        if(isset($level_child_datas)){
                                            foreach($level_child_datas as $data){
                                                if($data['id']!=$customer_id){
                                                    $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                    array_push($level_child_datas,$temp);
                                                }
                                            }
                                        }else{
                                            $level_child_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                        }
                                        $this->model_sale_customer->updateLevelChilden($customer_info['custormer_parent'],serialize($level_child_datas));
                                    }
                                }else{
                                    $this->model_sale_customer->updateIndexValueCustomer($customer_id,$value_index+1);
                                }
                            }
                            else{

                                if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                    $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                    if($customer_pr_info['level_childen']!=null)
                                    {
                                        $level_child_datas=unserialize($customer_pr_info['level_childen']);
                                    }
                                    // var_dump($level_child_datas);
                                    if(isset($level_child_datas)){
                                        foreach($level_child_datas as $data){
                                            if($data['id']!=$customer_id){
                                                $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                array_push($level_child_datas,$temp);
                                            }
                                        }
                                    }else{
                                        $level_child_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                    }
                                    $this->model_sale_customer->updateLevelChilden($customer_info['custormer_parent'],serialize($level_child_datas));

                                }
                                $this->model_sale_customer->updateIndexValueCustomer($customer_id,$value_index+1);
                            }

                        }
                    }
                    elseif($level==6){
                        $this->model_sale_customer->updateIndexValueCustomer($customer_id,$value_index+1);
                    }
               // }
            }

            if($level_nhanh == 0){
                if($value_index_nhanh == 49){
                    $this->model_sale_customer->updateLevelNhanhCustomer($customer_id,$level_nhanh+1);
                    if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                        $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                        if($customer_pr_info['level_childen_nhanh']!=null) {$level_child_datas=unserialize($customer_pr_info['level_childen_nhanh']);
                        }
                      //  var_dump($level_child_datas);
                        if(isset($level_child_datas)){
                            foreach($level_child_datas as $data){
                                if($data['id']!=$customer_id){
                                    $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                    array_push($level_child_datas,$temp);
                                }
                            }
                        }else{
                            $level_child_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                        }
                       // var_dump($level_child_datas);
                        //$temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                        $this->model_sale_customer->updateLevelChildenNhanh($customer_info['customer_parent'],serialize($level_child_datas));
                    }
                   $this->session->data['level_update'][$level_nhanh+1] = true;
                } else{
                    $this->model_sale_customer->updateIndexValueNhanhCustomer($customer_id,$value_index_nhanh+1);
                }

            }
            else {
              //  if(isset($this->session->data['level_update'][$level_nhanh])){
                    if($level_nhanh == 1){
                        if(isset($this->session->data['level_update'][$level_nhanh])){
                            if($level_childen_nhanh!=null){
                                $data_nhanh_childs=unserialize($level_childen_nhanh);
                                foreach($data_nhanh_childs as $data_child){
                                    if(in_array(1,$data_child['level']))
                                        $temp=true;
                                    break;
                                }
                                if(($temp)&&($value_index==1)){
                                    $this->model_sale_customer->updateLevelNhanhCustomer($customer_id,$level+1);
                                    $this->session->data['level_update'][$level_nhanh+1] = true;
                                    if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                        $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                        if($customer_pr_info['level_childen_nhanh']!=null)
                                        {
                                            $level_child_nhanh_datas=unserialize($customer_pr_info['level_childen_nhanh']);
                                        }
                                        // var_dump($level_child_datas);
                                        if(isset($level_child_nhanh_datas)){
                                            foreach($level_child_nhanh_datas as $data){
                                                if($data['id']!=$customer_id){
                                                    $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                    array_push($level_child_nhanh_datas,$temp);
                                                }
                                            }
                                        }else{
                                            $level_child_nhanh_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                        }
                                        $this->model_sale_customer->updateLevelChildenNhanh($customer_info['custormer_parent'],serialize($level_child_nhanh_datas));
                                    }
                                }else{
                                    $this->model_sale_customer->updateIndexValueNhanhCustomer($customer_id,$value_index+1);
                                }
                            }
                            else{
                                $this->model_sale_customer->updateIndexValueNhanhCustomer($customer_id,$value_index+1);
                                if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                    $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                    if($customer_pr_info['level_childen_nhanh']!=null)
                                    {
                                        $level_child_nhanh_datas=unserialize($customer_pr_info['level_childen_nhanh']);
                                    }
                                    // var_dump($level_child_datas);
                                    if(isset($level_child_nhanh_datas)){
                                        foreach($level_child_nhanh_datas as $data){
                                            if($data['id']!=$customer_id){
                                                $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                array_push($level_child_nhanh_datas,$temp);
                                            }
                                        }
                                    }else{
                                        $level_child_nhanh_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                    }
                                    $this->model_sale_customer->updateLevelChildenNhanh($customer_info['custormer_parent'],serialize($level_child_nhanh_datas));

                                }

                            }

                        }
                    } elseif($level_nhanh==2){
                        if(isset($this->session->data['level_update'][$level_nhanh])){
                            if($level_childen_nhanh!=null){
                                $data_nhanh_childs=unserialize($level_childen_nhanh);
                                foreach($data_nhanh_childs as $data_child){
                                    if(in_array(1,$data_child['level']))
                                        $temp=true;
                                    break;
                                }
                                if(($temp)&&($value_index==2)){
                                    $this->model_sale_customer->updateLevelNhanhCustomer($customer_id,$level+1);
                                    $this->session->data['level_update'][$level_nhanh+1] = true;
                                    if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                        $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                        if($customer_pr_info['level_childen_nhanh']!=null)
                                        {
                                            $level_child_nhanh_datas=unserialize($customer_pr_info['level_childen_nhanh']);
                                        }
                                        // var_dump($level_child_datas);
                                        if(isset($level_child_nhanh_datas)){
                                            foreach($level_child_nhanh_datas as $data){
                                                if($data['id']!=$customer_id){
                                                    $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                    array_push($level_child_nhanh_datas,$temp);
                                                }
                                            }
                                        }else{
                                            $level_child_nhanh_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                        }
                                        $this->model_sale_customer->updateLevelChildenNhanh($customer_info['custormer_parent'],serialize($level_child_nhanh_datas));
                                    }
                                }else{
                                    $this->model_sale_customer->updateIndexValueNhanhCustomer($customer_id,$value_index+1);
                                }
                            }
                            else{
                                $this->model_sale_customer->updateIndexValueNhanhCustomer($customer_id,$value_index+1);
                                if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                    $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                    if($customer_pr_info['level_childen_nhanh']!=null)
                                    {
                                        $level_child_nhanh_datas=unserialize($customer_pr_info['level_childen_nhanh']);
                                    }
                                    // var_dump($level_child_datas);
                                    if(isset($level_child_nhanh_datas)){
                                        foreach($level_child_nhanh_datas as $data){
                                            if($data['id']!=$customer_id){
                                                $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                array_push($level_child_nhanh_datas,$temp);
                                            }
                                        }
                                    }else{
                                        $level_child_nhanh_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                    }
                                    $this->model_sale_customer->updateLevelChildenNhanh($customer_info['custormer_parent'],serialize($level_child_nhanh_datas));

                                }

                            }

                        }
                    }elseif($level_nhanh==3){
						 if(isset($this->session->data['level_update'][$level_nhanh])){
                            if($level_childen_nhanh!=null){
                                $data_nhanh_childs=unserialize($level_childen_nhanh);
                                foreach($data_nhanh_childs as $data_child){
                                    if(in_array(1,$data_child['level']))
                                        $temp=true;
                                    break;
                                }
                                if(($temp)&&($value_index==1)){
                                    $this->model_sale_customer->updateLevelNhanhCustomer($customer_id,$level+1);
                                    $this->session->data['level_update'][$level_nhanh+1] = true;
                                    if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                        $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                        if($customer_pr_info['level_childen_nhanh']!=null)
                                        {
                                            $level_child_nhanh_datas=unserialize($customer_pr_info['level_childen_nhanh']);
                                        }
                                        // var_dump($level_child_datas);
                                        if(isset($level_child_nhanh_datas)){
                                            foreach($level_child_nhanh_datas as $data){
                                                if($data['id']!=$customer_id){
                                                    $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                    array_push($level_child_nhanh_datas,$temp);
                                                }
                                            }
                                        }else{
                                            $level_child_nhanh_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                        }
                                        $this->model_sale_customer->updateLevelChildenNhanh($customer_info['custormer_parent'],serialize($level_child_nhanh_datas));
                                    }
                                }else{
                                    $this->model_sale_customer->updateIndexValueNhanhCustomer($customer_id,$value_index+1);
                                }
                            }
                            else{
                                $this->model_sale_customer->updateIndexValueNhanhCustomer($customer_id,$value_index+1);
                                if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                    $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                    if($customer_pr_info['level_childen_nhanh']!=null)
                                    {
                                        $level_child_nhanh_datas=unserialize($customer_pr_info['level_childen_nhanh']);
                                    }
                                    // var_dump($level_child_datas);
                                    if(isset($level_child_nhanh_datas)){
                                        foreach($level_child_nhanh_datas as $data){
                                            if($data['id']!=$customer_id){
                                                $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                array_push($level_child_nhanh_datas,$temp);
                                            }
                                        }
                                    }else{
                                        $level_child_nhanh_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                    }
                                    $this->model_sale_customer->updateLevelChildenNhanh($customer_info['custormer_parent'],serialize($level_child_nhanh_datas));

                                }

                            }

                        }
                    }elseif($level_nhanh==4){
						 if(isset($this->session->data['level_update'][$level_nhanh])){
                            if($level_childen_nhanh!=null){
                                $data_nhanh_childs=unserialize($level_childen_nhanh);
                                foreach($data_nhanh_childs as $data_child){
                                    if(in_array(1,$data_child['level']))
                                        $temp=true;
                                    break;
                                }
                                if(($temp)&&($value_index==1)){
                                    $this->model_sale_customer->updateLevelNhanhCustomer($customer_id,$level+1);
                                    $this->session->data['level_update'][$level_nhanh+1] = true;
                                    if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                        $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                        if($customer_pr_info['level_childen_nhanh']!=null)
                                        {
                                            $level_child_nhanh_datas=unserialize($customer_pr_info['level_childen_nhanh']);
                                        }
                                        // var_dump($level_child_datas);
                                        if(isset($level_child_nhanh_datas)){
                                            foreach($level_child_nhanh_datas as $data){
                                                if($data['id']!=$customer_id){
                                                    $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                    array_push($level_child_nhanh_datas,$temp);
                                                }
                                            }
                                        }else{
                                            $level_child_nhanh_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                        }
                                        $this->model_sale_customer->updateLevelChildenNhanh($customer_info['custormer_parent'],serialize($level_child_nhanh_datas));
                                    }
                                }else{
                                    $this->model_sale_customer->updateIndexValueNhanhCustomer($customer_id,$value_index+1);
                                }
                            }
                            else{
                                $this->model_sale_customer->updateIndexValueNhanhCustomer($customer_id,$value_index+1);
                                if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                    $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                    if($customer_pr_info['level_childen_nhanh']!=null)
                                    {
                                        $level_child_nhanh_datas=unserialize($customer_pr_info['level_childen_nhanh']);
                                    }
                                    // var_dump($level_child_datas);
                                    if(isset($level_child_nhanh_datas)){
                                        foreach($level_child_nhanh_datas as $data){
                                            if($data['id']!=$customer_id){
                                                $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                array_push($level_child_nhanh_datas,$temp);
                                            }
                                        }
                                    }else{
                                        $level_child_nhanh_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                    }
                                    $this->model_sale_customer->updateLevelChildenNhanh($customer_info['custormer_parent'],serialize($level_child_nhanh_datas));

                                }

                            }

                        }
                    }elseif($level_nhanh==5){
						 if(isset($this->session->data['level_update'][$level_nhanh])){
                            if($level_childen_nhanh!=null){
                                $data_nhanh_childs=unserialize($level_childen_nhanh);
                                foreach($data_nhanh_childs as $data_child){
                                    if(in_array(1,$data_child['level']))
                                        $temp=true;
                                    break;
                                }
                                if(($temp)&&($value_index==1)){
                                    $this->model_sale_customer->updateLevelNhanhCustomer($customer_id,$level+1);
                                    $this->session->data['level_update'][$level_nhanh+1] = true;
                                    if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                        $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                        if($customer_pr_info['level_childen_nhanh']!=null)
                                        {
                                            $level_child_nhanh_datas=unserialize($customer_pr_info['level_childen_nhanh']);
                                        }
                                        // var_dump($level_child_datas);
                                        if(isset($level_child_nhanh_datas)){
                                            foreach($level_child_nhanh_datas as $data){
                                                if($data['id']!=$customer_id){
                                                    $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                    array_push($level_child_nhanh_datas,$temp);
                                                }
                                            }
                                        }else{
                                            $level_child_nhanh_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                        }
                                        $this->model_sale_customer->updateLevelChildenNhanh($customer_info['custormer_parent'],serialize($level_child_nhanh_datas));
                                    }
                                }else{
                                    $this->model_sale_customer->updateIndexValueNhanhCustomer($customer_id,$value_index+1);
                                }
                            }
                            else{
                                $this->model_sale_customer->updateIndexValueNhanhCustomer($customer_id,$value_index+1);
                                if(isset($customer_info['customer_parent']) && $customer_info['customer_parent']!=0){
                                    $customer_pr_info=$this->model_sale_customer->getCustomer($customer_info['custormer_parent']);
                                    if($customer_pr_info['level_childen_nhanh']!=null)
                                    {
                                        $level_child_nhanh_datas=unserialize($customer_pr_info['level_childen_nhanh']);
                                    }
                                    // var_dump($level_child_datas);
                                    if(isset($level_child_nhanh_datas)){
                                        foreach($level_child_nhanh_datas as $data){
                                            if($data['id']!=$customer_id){
                                                $temp = array('id'=>$customer_id,'level'=>array('0'=>1));
                                                array_push($level_child_nhanh_datas,$temp);
                                            }
                                        }
                                    }else{
                                        $level_child_nhanh_datas = array(0=> array('id'=>$customer_id,'level'=>array('0'=>1)));
                                    }
                                    $this->model_sale_customer->updateLevelChildenNhanh($customer_info['custormer_parent'],serialize($level_child_nhanh_datas));

                                }

                            }

                        }
                    }elseif($level_nhanh==6){
                        $this->model_sale_customer->updateIndexValueNhanhCustomer($customer_id,$value_index_nhanh+1);
                    }
                    unset($this->session->data['level_update'][$level_nhanh]);
                }

            }

            if ($customer_info['customer_parent']!=0){
                $this->updateNhanh($customer_info['customer_parent']);
            }
        }
    }
	public function updateNhanhAfterRecieve(){
		$this->language->load('sale/customer');
		$this->document->setTitle($this->language->get('heading_title'));
		$this->load->model('sale/customer');

		if(isset($this->request->post['customer_id'])){
			$customer_id = $this->request->post['customer_id'];
			//print($customer_id);die;
			$customer_info = $this->model_sale_customer->getCustomer($customer_id);
			if($customer_info){
				$level = $customer_info['level1'];
				$level_nhanh = $customer_info['level2'];
				$value_index = $customer_info['index_value1'];
				$value_index_nhanh = $customer_info['index_value2'];
				$level_childen = $customer_info['level_childen'];
				$level_childen_nhanh = $customer_info['level_childen_nhanh'];
				$level_update = 0;
				$count_level =0;
				$count1 = $count2 = $count3 = $count4 = $count5 =0;
				$count_level1= 0;//print_r($customer_info);die;
				$count_level2= 0;
				$count_level3= 0;
				$count_level4= 0;
				$count_level5= 0;
				if($level_childen!=null)
				{
					$level_child_datas=unserialize($level_childen);
					if($level ==1){
						$this->dacap->dfs(5);
						$countLevel0 = $this->dacap->countLevel0;
						//$countLevel0 = $this->dacap->visited;
						//print_r($countLevel0);
						if($countLevel0>=49){
							$level_update = 1;
							$count_level = $value_index;
						}
						else{
							$level_update = 0;
							$count_level = $countLevel0;
						}
						$this->model_sale_customer->updateLevelCustomer($customer_id,$level_update,0);
						if($level_update != $level){
							$this->model_sale_customer->updateIndexValueCustomer($customer_id,$count_level,0);
						}
					}
					//print_r($level_child_datas);
					if($level_child_datas!=null){
						$level_temp = $level;

						if($level >=2){
							$flag = false;
							foreach($level_child_datas as $key => $value){
								$temp_value = explode(":",$value);
								foreach($temp_value as $val){
									if($val >= 5){
										$count_level5++;
										if($val == 5){
											$count5++;
										}
									}elseif($val >=4){
										$count_level4++;
										if($val == 4){
											$count4++;
										}
									}elseif($val >=3){
										$count_level3++;
										if($val == 3){
											$count3++;
										}
									}elseif($val >=2){
										$count_level2++;
										if($val == 2){
											$count2++;
										}
									}elseif($val >=1){
										$count_level1++;
										if($val == 1){
											$count1++;
										}
									}
								}
							}
							if($count_level1 >= 2){
								$level_update = 2;
								$count_level = $count2;
							}
							if($count_level2 >= 3){
								$level_update = 3;
								$count_level = $count3;
							}
							if($count_level3 >= 3){
								$level_update = 4;
								$count_level = $count4;
							}
							if($count_level4 >= 4){
								$level_update = 5;
								$count_level = $count5;
							}
							if($count_level5 >= 8){
								$level_update = 6;
							}
							$this->model_sale_customer->updateLevelCustomer($customer_id,$level_update,0);
							if($level_update != $level){
								$this->model_sale_customer->updateIndexValueCustomer($customer_id,$count_level,0);
							}
						}
					}
				}
			}
		}
	}
	public function updateNhanh($customer_id){
		//Gia tri de update cho nhanh.
		$customer_info = $this->model_sale_customer->getCustomer($customer_id);
		$level_nhanh = $customer_info['level2'];
		$value_index_nhanh = $customer_info['index_value2'];
		$level_childen_nhanh = $customer_info['level_childen_nhanh'];
		try {
			//UPdate level cho thanh vien
			//$this->db->beginTransaction();
			$this->updateLevel($customer_info,$type = 0);
			//UPdate level cho nhanh
			$this->updateLevel($customer_info,$type = 1);
			//$this->db->commit();	
		} catch (Exception $e) {
			//$this->db->rollBack();
		}
		
		if($customer_info['customer_parent']){
			$this->session->data['customer_id_child'] = $customer_id;
			$this->updateNhanh($customer_info['customer_parent']);
		}
		unset($this->session->data['customer_id_child']);
		unset($this->session->data['level']);
    }
	function updateLevel($customer_info,$type = 0){
		//$customer_info = $this->model_sale_customer->getCustomer($customer_info);
		if($type){
			//Gia tri cho nhanh
			$level = $customer_info['level2'];
			$value_index = $customer_info['index_value2'];
			if((int)$level == 0){
				if($this->updateLevelByLevel0($customer_info['customer_id'],$value_index,$type)){
					//$this->session->data['customer_id_child'] = "";
					if(!in_array(1,$this->session->data['level'])){
						$this->session->data['level'][] = 1;
					}
				}
			} else {
			//todo trint st
				if(!isset($this->session->data['customer_id_child'])){
					$this->session->data['customer_id_child'] = array();					
				}
				if(!isset($this->session->data['level'])){
					$this->session->data['level'] = array();
				}
			//trint en
				$level_childen = unserialize($customer_info['level_childen_nhanh']);
				//print_r($this->session->data['customer_id_child']);die;
				if($level_childen  && isset($level_childen[$this->session->data['customer_id_child']]) && $level_childen[$this->session->data['customer_id_child']]){
					$temp_array = explode(':',$level_childen[$this->session->data['customer_id_child']]);
					//$level_childen[$this->session->data['customer_id_child']] = $this->pushLevelCustomerToArray($temp_array,$this->session->data['level']);
					
					if(!in_array($level,$temp_array)){
						if($this->session->data['level']){
							$level_childen[$this->session->data['customer_id_child']].= ":" . (string)implode(":",$this->session->data['level']);
							$this->model_sale_customer->updateLevelChildenNhanh($customer_info['customer_id'],serialize($level_childen));
						}						
						//$this->updateLevelByLevelDifferent0($customer_info['customer_id'],$level,$value_index,$level_childen,$type);
					}
				} else {//print_r($this->session->data['level']);
					if($this->session->data['level']){
						$level_childen[$this->session->data['customer_id_child']] = implode(':',$this->session->data['level']);
						$this->model_sale_customer->updateLevelChildenNhanh($customer_info['customer_id'],serialize($level_childen));						
						
					}
					if($this->session->data['first_customer_parent'] == $customer_info['customer_id']){
						$this->updateLevelByLevelDifferent0($customer_info['customer_id'],$level,$value_index,$level_childen,$type);
					}
				}
				
				$this->updateIndexValueWhenUpdateLevel($customer_info['customer_id'],$type);
				$key = array_search($level, $this->session->data['level']);
				if (false !== $key) {
					unset($this->session->data['level'][$key]);
				}
			}
		} else {
			//Gia tri cho thanh vien
			$level = $customer_info['level1'];
			$value_index = $customer_info['index_value1'];
			if((int)$level == 0){
			//trint
				//$this->session->data['customer_id_child'] = "";
				$this->updateLevelByLevel0($customer_info['customer_id'],$value_index,$type);
			} else {
			//todo trint st
				if(!isset($this->session->data['customer_id_child'])){
					$this->session->data['customer_id_child'] = array();					
				}
				if(!isset($this->session->data['level'])){
					$this->session->data['level'] = array();
				}
			//trint en
				$level_childen = unserialize($customer_info['level_childen']);
				if($level_childen && isset($level_childen[$this->session->data['customer_id_child']]) && $level_childen[$this->session->data['customer_id_child']]){
					$temp_array = explode(':',$level_childen[$this->session->data['customer_id_child']]);
					//$level_childen[$this->session->data['customer_id_child']] = $this->pushLevelCustomerToArray($temp_array,$this->session->data['level']);
					
					if(!in_array($level,$temp_array)){
						if($this->session->data['level']){
							$level_childen[$this->session->data['customer_id_child']].= ":" . (string)implode(":",$this->session->data['level']);
							$this->model_sale_customer->updateLevelChildenNhanh($customer_info['customer_id'],serialize($level_childen));
						}	
					    $this->model_sale_customer->updateLevelChilden($customer_info['customer_id'],serialize($level_childen));
						//$this->updateLevelByLevelDifferent0($customer_info['customer_id'],$level,$value_index,$level_childen,$type);
					}
				} else {
					if($this->session->data['level']){
						$level_childen[$this->session->data['customer_id_child']] = implode(':',$this->session->data['level']);
						$this->model_sale_customer->updateLevelChilden($customer_info['customer_id'],serialize($level_childen));						
					}	
					if($this->session->data['first_customer_parent'] == $customer_info['customer_id']){
						$this->updateLevelByLevelDifferent0($customer_info['customer_id'],$level,$value_index,$level_childen,$type);
					}
				}
				$this->updateIndexValueWhenUpdateLevel($customer_info['customer_id'],$type);
			}
		}
	}

	function updateLevelByLevel0($customer_id,$value_index,$type){
		if((int)$value_index == 4) {//todo trint
			$this->model_sale_customer->updateLevelCustomer($customer_id,1,$type);
			return 1;
		} else {
			$this->model_sale_customer->updateIndexValueCustomer($customer_id,$value_index+1,$type);
			return 0;
		}
	}

	function updateLevelByLevelDifferent0($customer_id,$level,$value_index,$level_childen,$type){
		if($this->checIsUpdateLevel($level,$value_index)){
			//Tang cap cho thanh vien
			$this->model_sale_customer->updateLevelCustomer($customer_id,$level+1,$type);
			if($type){
				$this->session->data['level'][] = $level + 1;
				return true;
			}
		} else {
			//Cap nhap value_index cho thanh vien
			if($this->session->data['first_customer_parent'] == $customer_id){
				$this->model_sale_customer->updateIndexValueCustomer($customer_id,$value_index+1,$type);
				return false;
			}
		}
	}

	public function checIsUpdateLevel($level,$value_index){
	//todo
		switch ((int)$level){
			case 1:
				if($value_index == 2){
					return true;
				}
				return false;
			case 2:
				if($value_index == 3){
					return true;
				}
				return false;
			case 3:
				if($value_index == 3){
					return true;
				}
				return false;
			case 4:
				if($value_index == 4){
					return true;
				}
				return false;
			case 5:
				if($value_index == 8){
					return true;
				}
				return false;
		}
	}
	function updateIndexValueWhenUpdateLevel($customer_id,$type){
		$customer_info = $this->model_sale_customer->getCustomer($customer_id);
		if($type){
			if(isset($customer_info)){
				$level = $customer_info['level2'];
				$value_index= $customer_info['index_value2'];
				$level_child_datas=unserialize($customer_info['level_childen_nhanh']);
				$count = 0;
				if($level_child_datas){
					foreach($level_child_datas as $key => $value){
						$temp_value = explode(":",$value);
						if(in_array($level,$temp_value)){
							$count++;
						}
					}
					$this->model_sale_customer->updateIndexValueCustomer($customer_info['customer_id'],$count,$type);
				}
				if($this->checIsUpdateLevel($level,$count)){
					$this->model_sale_customer->updateLevelCustomer($customer_id,$level+1,$type);
					if($type){
						$this->session->data['level'][] = $level + 1;
						return true;
					}
				}
			}
		}else{
			if(isset($customer_info)){
				$level = $customer_info['level1'];
				$value_index= $customer_info['index_value1'];
				$level_child_datas=unserialize($customer_info['level_childen']);
				$count = 0;
				if($level_child_datas){
					foreach($level_child_datas as $key => $value){
						$temp_value = explode(":",$value);
						if(in_array($level,$temp_value)){
							$count++;
						}
					}
					$this->model_sale_customer->updateIndexValueCustomer($customer_info['customer_id'],$count,$type);
				}	
				if($this->checIsUpdateLevel($level,$count)){
					$this->model_sale_customer->updateLevelCustomer($customer_id,$level+1,$type);					
				}
			}
		}
	}
	function pushLevelCustomerToArray($temp_array = array(),$array = array()){
		return array_push($temp_array,$array);		 
	}
}
?>